package com.capgemini.diabeo.activity;

import java.util.ArrayList;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;

import com.capgemini.diabeo.R;
import com.capgemini.diabeo.manager.DishManager;
import com.capgemini.diabeo.model.Menu;
import com.capgemini.diabeo.model.MenuDish;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.ViewById;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

@EActivity(R.layout.activity_graphic)
public class GraphicActivity extends Activity {

	@ViewById
	LinearLayout layoutGraph;

	@ViewById
	Button barChartButton;

	@ViewById
	Button pieChartButton;

	@Bean
	DishManager dishManager;
	
	float totalGlucides = 0;

	/*	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.graphic, menu);
		return true;
	}*/
	
	@AfterViews
	public void afterViews()
	{
		final GraphicalView gvPie = pieChartDrawing();
		layoutGraph.addView(gvPie);
	}

	@Click
	public void barChartButtonClicked(View view) {
		layoutGraph.removeAllViews();
		Menu currentMenu = dishManager.getCurrentMenu();
		if(currentMenu != null)
		{
			String mealTime = currentMenu.getMealTime();
			totalGlucides = (float)currentMenu.getTotalCarbohydrate();
			final GraphicalView gvBar = createIntent(totalGlucides, mealTime);
			layoutGraph.addView(gvBar);
		}
	}

	@Click
	public void pieChartButtonClicked(View view) {
		
		layoutGraph.removeAllViews();
		final GraphicalView gvPie = pieChartDrawing();
		
		gvPie.setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View v) {
	      SeriesSelection seriesSelection = gvPie.getCurrentSeriesAndPoint();
	      if (seriesSelection != null) {
	       Toast.makeText(GraphicActivity.this, seriesSelection.getValue() + "g de Glucides",
	            Toast.LENGTH_SHORT).show();
	      }
	    }
	  });
		
		layoutGraph.addView(gvPie);
	}
	
	public GraphicalView pieChartDrawing()
	{
		Menu currentMenu = dishManager.getCurrentMenu();
		ArrayList<Double> dishesCarbohydrate = new ArrayList<Double>();
		ArrayList<String> dishesNames = new ArrayList<String>();
		for (MenuDish menuDish : currentMenu.getMenuDishList()) {
			dishesCarbohydrate.add(menuDish.getDish().getCarbohydrate());
			dishesNames.add(menuDish.getDish().getName());
		}
		final GraphicalView gvPie = openPieChart(dishesCarbohydrate, dishesNames);
		return gvPie;
	}

	/*** Librarie AChartengine ***/
	public GraphicalView createIntent(float totalGlucides, String mealtime) {
		String[] titles = new String[] { "Glucides (g)"};
		List<double[]> values = new ArrayList<double[]>();

		//	values.add(new double[] { totalGlucides, totalIg, totalLipides,10230, 11300, 10040,14230, 12300, 14240, 11300, 10040,14240});
		values.add(new double[] { totalGlucides});

		int[] colors = new int[] { Color.parseColor("#77c4d3")};
		XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);
		renderer.setOrientation(Orientation.HORIZONTAL);
		setChartSettings(renderer, "Glucides des repas", "Temps", "Glucides (g)", 0.5,
				2, 0, 100, Color.BLACK, Color.BLACK);
		renderer.setXLabels(1);
		renderer.setYLabels(10);
		renderer.addXTextLabel(1, mealtime);
		renderer.addXTextLabel(2, "Midi 25/03");
		int length = renderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++) {
			SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
			seriesRenderer.setDisplayChartValues(true);
		}

		final GraphicalView grfv = ChartFactory.getBarChartView(this, buildBarDataset(titles, values), renderer,Type.DEFAULT);

		return grfv;
	}
	protected XYMultipleSeriesRenderer buildBarRenderer(int[] colors) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setAxisTitleTextSize(16);
		renderer.setChartTitleTextSize(20);
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setBarSpacing(0.5f);

		renderer.setMarginsColor(Color.parseColor("#EEEDED"));
		renderer.setXLabelsColor(Color.BLACK);
		renderer.setYLabelsColor(0,Color.BLACK);

		renderer.setApplyBackgroundColor(true);
		renderer.setBackgroundColor(Color.parseColor("#FBFBFC"));

		int length = colors.length;
		for (int i = 0; i < length; i++) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(colors[i]);
			r.setChartValuesSpacing(15);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}
	protected XYMultipleSeriesDataset buildBarDataset(String[] titles, List<double[]> values) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			CategorySeries series = new CategorySeries(titles[i]);
			double[] v = values.get(i);
			int seriesLength = v.length;
			for (int k = 0; k < seriesLength; k++) {
				series.add(v[k]);
			}
			dataset.addSeries(series.toXYSeries());
		}
		return dataset;
	}

	protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle,
			String yTitle, double xMin, double xMax, double yMin, double yMax, int axesColor,
			int labelsColor) {
		renderer.setChartTitle(title);
		renderer.setYLabelsAlign(Align.RIGHT);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		renderer.setPanEnabled(false);
		renderer.setZoomEnabled(false);
		renderer.setMargins(new int[] { 10, 65, 10, 15 });
		renderer.setAxesColor(axesColor);
		renderer.setLabelsColor(labelsColor);
	}

	/***Pie Chart 
	 * @return **/
	private GraphicalView openPieChart(ArrayList<Double> distribution, ArrayList<String> code){

		// Color of each Pie Chart Sections
		int[] colors = { Color.BLUE, Color.MAGENTA, Color.GREEN, Color.CYAN, Color.RED,
				Color.YELLOW };
		//int[] colors = { R.color.graph1, R.color.graph2, R.color.graph3, R.color.graph4, R.color.graph5, R.color.graph6 };

		// Instantiating CategorySeries to plot Pie Chart
		CategorySeries distributionSeries = new CategorySeries(" Gramme de Glucide par plat dans un repas");
		for(int i=0 ;i < distribution.size();i++){
			// Adding a slice with its values and name to the Pie Chart
			distributionSeries.add(code.get(i), distribution.get(i));
		}

		// Instantiating a renderer for the Pie Chart
		DefaultRenderer defaultRenderer  = new DefaultRenderer();
		for(int i = 0 ;i<distribution.size();i++){
			SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
			seriesRenderer.setColor(colors[i]);
			seriesRenderer.setDisplayChartValues(true);
			// Adding a renderer for a slice
			defaultRenderer.addSeriesRenderer(seriesRenderer);
		}

		defaultRenderer.setChartTitle(" Gramme de Glucide par plat dans un repas");
		defaultRenderer.setChartTitleTextSize(30);
		defaultRenderer.setStartAngle(15);
		defaultRenderer.setLegendTextSize(30);
		defaultRenderer.setLabelsColor(Color.BLACK);
		defaultRenderer.setLabelsTextSize(30);
		defaultRenderer.setClickEnabled(true);
		defaultRenderer.setSelectableBuffer(10);
		defaultRenderer.setShowLabels(false);
		defaultRenderer.setPanEnabled(false);
		defaultRenderer.setZoomButtonsVisible(false);

		final GraphicalView grfv = ChartFactory.getPieChartView(getBaseContext(), distributionSeries, defaultRenderer);

		return grfv;

	}
}
